package tuvienna.jade;

import java.util.Collection;
import java.util.Iterator;
import java.util.Map;

public abstract class Tools {
	/**
	 * 
	 * Should return very low prob for young age, increase dramatically around median age
	 * and get too almost 1 for value far older than median age.
	 * @param age current age
	 * @param medianAge The age that should have 0.5 prob
	 * @return
	 */
	public static double getTooOldProbability(double age, double medianAge) {
		return getTooOldProbability(age, medianAge, 5/medianAge); 
	}
	
	public static double getTooOldProbability(double age, double medianAge, double scale) {
		return 1/(1 + Math.pow(Math.E, - ((age - medianAge) * scale))); 
	}
	
	public static <T> T getBestByScore(Map<T, Double> map ) {
		if (map.size() == 0) {
			throw new RuntimeException("Map is empty");
		}
		
		Double bestScore = null; 
		T best = null;

		for (T entry:map.keySet()) {
			if (bestScore == null || bestScore< map.get(entry)) {
				bestScore =  map.get(entry);
				best = entry;
			}
		}
		return best;
	}
	
	public static <T> T getRandomByScore(Map<T, Double> map ) {
		
		if (map.size() == 0) {
			throw new RuntimeException("Map is empty");
		}
		
		double sum = 0;
		for (double d:map.values()) {
			sum+=d;
		}
		if (sum > 0) {
			double randomChoice = sum * CentralRandom.nextDouble();
			double pos =0;
			for (T entry:map.keySet()) {
				pos+=map.get(entry);
				if (pos >= randomChoice) {
					return entry;
				}
			}
		}
		// no scores pick pure randomly
		return getRandom(map.keySet());
	}
		
	public static<T> T getRandom(Collection<T> collection) {
		int entryNo = CentralRandom.nextInt(collection.size());
		Iterator<T> iter = collection.iterator();
		for (int i=0; i<entryNo; i++) {
			iter.next();
		}
		return iter.next();
	}
	
}
